//
//  HLDiscoverSearchView.swift
//  HLWeiBo
//
//  Created by jack on 15/12/5.
//  Copyright © 2015年 jack. All rights reserved.
//

import UIKit

class HLDiscoverSearchView: UIView ,UITextFieldDelegate{
    
    @IBOutlet weak var searchTextField: UITextField!

    @IBOutlet weak var cancelBtn: UIButton!

    @IBOutlet weak var trailingConstraint: NSLayoutConstraint!
    
    //从xib加载
    class func searchView () -> HLDiscoverSearchView {
    
        return NSBundle.mainBundle().loadNibNamed("HLDiscoverSearchView", owner: nil, options: nil).last as! HLDiscoverSearchView
        
    }
    //用代码创建控件有关
    override init(frame: CGRect) {
        
        super.init(frame: frame)
    }
    //通过xib连线会调用这个方法
    override func awakeFromNib() {
        let leftView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        leftView.frame = CGRect(x: 0, y: 0, width: frame.height, height: frame.height)
        //设置内容显示模式
        leftView.contentMode = .Center
        
        searchTextField.leftView = leftView
        
        searchTextField.leftViewMode = UITextFieldViewMode.Always
    }
    
    //用代码向当前控件添加子控件
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    @IBAction func cancelBtn(sender: UIButton) {
        
        searchTextField.resignFirstResponder()
        //法2
//        searchTextField.endEditing(true)
        
        trailingConstraint.constant = 0
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.searchTextField.layoutIfNeeded()
        }
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        
//        searchTextField.becomeFirstResponder()
        
        trailingConstraint.constant = self.cancelBtn.frame.width
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.searchTextField.layoutIfNeeded()
        }
    }
}
